package com.tensquare.user.service;

import com.tensquare.user.dao.UserDao;
import com.tensquare.user.pojo.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by WF on 2019/9/21 10:40
 */
@Service
@Transactional
public class UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private UserDao userDao;
    //1.发送手机验证码
    public void sendCode(String mobile) {
        //1.1)生成六位数的验证码
        int min = 100000;
        int max = 999999;
        Random random = new Random();
        //生在一个(0-899999)范围的随机数
        int i = random.nextInt(max - min);
        //得到六位数的验证码
        String code = (min + i) + "";

        //1.2)将验证码放到redis中
        redisTemplate.opsForValue().set(mobile,code,5,TimeUnit.MINUTES);

        //1.3)向springboot短信验证码的微服务后台发送消息
        Map map = new HashMap<>();
        map.put("mobile",mobile);
        map.put("code",code);
        rabbitTemplate.convertAndSend("sms",map);
    }

    //2.添加用户
    public void add(User user) {
        //2.1)设置id
        user.setId(idWorker.nextId() + "");
        //2.2)加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //2.3)添加到数据库中
        userDao.save(user);
    }
    //3.用户登录
    public User login(User user) {
        //3.1)根据手机号得到用户
        User u = userDao.findByMobile(user.getMobile());
        //3.2)如果存在此用户，就判断密码是否一致
        if(u != null && passwordEncoder.matches(user.getPassword(),u.getPassword())){
            return u;
        }
        //3.3)返回null
        return null;
    }
    //4.删除用户
    public void delete(String userId) {
        userDao.deleteById(userId);
    }
    //5.更新粉丝数
    public void incfans(String friendid, int x) {
        userDao.incfans(friendid,x);
    }
    //6.更新关注数
    public void incfollow(String userid, int x) {
        userDao.incfollow(userid,x);
    }
}
